package com.barunsw.bwf.ems.common.controller;

import java.security.Principal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;

import com.barunsw.bwf.ems.common.model.AlarmMessage;
import com.barunsw.bwf.ems.common.model.SimpleMessage;

/**
 * {@link WebSocketBroadcastController} is a regular Spring Controller as seen
 * in most Spring MVC applications. Its job is to receive {@link SimpleMessage}
 * message objects from the client, extract the <code>payload</code> (or
 * contents) of the message, prepend it with some simple text and finally
 * broadcast (or publish) the message to all clients who have subscribed to the
 * <code>/topic/simplemessages</code> message queue.
 * 
 * 
 * @author <a href="mailto:sunitkatkar@gmail.com">Sunit Katkar</a>
 * @since 1.0
 * @version 1.0.0.1
 */

@Controller
public class WebSocketBroadcastController {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketBroadcastController.class);

    @MessageMapping("/alarmmessages")
    @SendTo("/topic/alarmmessagesresponse")
    public AlarmMessage processAlarmMessageFromClient(AlarmMessage message,
            Principal principal) throws Exception {
        // Simulate a delay of 3 seconds
        LOGGER.info("Sending server side response '{}' for user: {}", message,
                principal.getName());

        return message;
    }

    /**
     * If there are any exceptions thrown by any of the messaging infrastructure
     * then they can be sent to the end user on the <code>/queue/errors</code>
     * destination.
     * 
     * @param exception
     * @return
     */
    @MessageExceptionHandler
    @SendToUser("/queue/errors")
    public String handleException(Throwable exception) {
        return exception.getMessage();
    }
}